<template>
    <div class="repair">
        <MyHeader></MyHeader>
        <van-form
            show-error
            scroll-to-error
            label-width="25vw"
            @submit="onSubmit"
            @failed="onFailed" 
        >
            <my-title>使用人信息</my-title>
            <van-field 
                v-model="formData.gsy_ex1" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex1" 
                label="使用人姓名"
                placeholder="使用人姓名" 
                :rules="[{ required: true, message: '请填写使用人姓名' }]"
            />
            <my-title>祭祀信息</my-title>
            <FieldPopupDatePicker 
                v-model:field="formData.gsy_dat1" 
                :minDate="new Date()"
                name="gsy_dat1" 
                label="祭扫日期" 
                :readonly="isReadonly"
            />

            <van-field 
                v-model="formData.gsy_ex4" 
                :readonly="isReadonly"
                type="number"
                required
                center
                name="gsy_ex4" 
                label="祭扫人数"
                placeholder="祭扫人数" 
                :rules="[{ required: true, message: '请填写祭扫人数' }]"
            />
            <my-title>预约人信息</my-title>
            <van-field 
                v-model="formData.gsy_ex2" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex2" 
                label="预约人姓名"
                placeholder="预约人姓名" 
                :rules="[{ required: true, message: '请填写预约人姓名' }]"
            >
                <template 
                    v-if="!isReadonly" 
                    #button
                >
                    <van-uploader 
                        v-model="dataArr.sh_ex37" 
                        :readonly="isReadonly"
                        :preview-image="false" 
                        :before-delete="beforeDelete('sh_ex37')" 
                        :before-read="beforeRead" 
                        :after-read="afterRead('sh_ex37', true)"
                    >
                        <van-button 
                            size="small" 
                            icon="plus" 
                            type="primary" 
                            native-type="button"
                        >
                            拍照识别
                        </van-button>
                    </van-uploader>
                </template>
            </van-field>
            <van-field 
                v-model="formData.gsy_ex3" 
                :readonly="isReadonly"
                required
                center
                type="number" 
                maxlength="11"
                name="gsy_ex3" 
                label="联系电话"
                placeholder="联系电话" 
                :rules="[{ required: true, message: '请填写联系电话' },{ validator: isPhone, message: '请填写正确的联系电话' }]"
            />

            <van-field 
                v-model="formData.gsy_ex5" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex5" 
                label="预约人身份证"
                placeholder="预约人身份证" 
                :rules="[{ required: true, message: '请填写预约人身份证' },{ validator: validator3, message: '请填写正确的预约人身份证' }]"
            />
            <!-- <van-field 
                required
                readonly
                center
                name="sh_ex37" 
                label="预约人身份证"
                :rules="[{ validator: validator2('sh_ex37'), message: '请上传预约人身份证' }]"
            />
            <div class="uploader-box">
                <van-uploader 
                    v-model="dataArr.sh_ex37" 
                    :readonly="isReadonly"
                    :max-count="1" 
                    upload-text="预约人身份证" 
                    :before-delete="beforeDelete('sh_ex37')" 
                    :before-read="beforeRead" 
                    :after-read="afterRead('sh_ex37')"
                    :deletable="!isReadonly"
                >
                    <template #default>
                        <img src="@/assets/uploader/uploader.png" />
                    </template>
                </van-uploader>
            </div> -->
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import MyHeader from '@/components/MyHeader.vue'
    import FixedButton from '@/components/FixedButton.vue'
    import FieldPopupPicker from '@/components/FieldPopupPicker.vue'
    import FieldPopupDatePicker from '@/components/FieldPopupDatePicker.vue'
    import FieldPopupEsign from '@/components/FieldPopupEsign.vue'
    import { useWeixinLogin3 } from '@/hooks'

    import { GmsmyuyApi, fileUploadBase64Ex, idOrc } from '@/apis'
    import { isPhone, compressImg, isCardID, getSex, getAge } from '@/utils/utils.js'
    import { useStore } from '@/store'
    // 微信授权并且跳转到对应页面
    useWeixinLogin3('sweepGraveAppointment')
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const isReadonly: boolean = false
    const formData = ref({
        gsy_ex1: '',
        gsy_ex3: '',
        gsy_ex2: '',
        gsy_ex5: '',
        sh_ex37: '',
        gsy_ex4: '',
        gsy_dat1: '',
        token: store.openid
    })
    const dataArr = reactive({
        sh_ex37: [], //预约人身份证
    })
    
    // 照片数组验证
    const validator2 = (field) => {
        return val => {
            console.log(val)
            console.log(field)
            if (dataArr[field].length == 0 || !formData.value[field]) {
                return false
            } else {
                return true
            }
        }
    }
    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator3 = (val) => {
        if (isCardID(val)) {
            return false
        } else {
            return true
        }
    }
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',')
            arr.splice(detail.index, 1)
            formData.value[data] = arr.join(',')
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64Ex({
            data: obj,
            sCode: 'fhsxbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'sh_ex37') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (dataArr[imgField].length > 1) {
                    dataArr[imgField].shift()
                }
                formData.value[imgField] = res[0].url
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrc({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            if (imgField == 'sh_ex37') {
                                formData.value.gsy_ex2 = obj['姓名'].words
                                formData.value.gsy_ex5 = obj['公民身份号码'].words
                            }
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                // formData.value[imgField] = res[0].url
                if (formData.value[imgField]) {
                    formData.value[imgField] = formData.value[imgField].concat(',', res[0].url)
                } else {
                    formData.value[imgField] = formData.value[imgField].concat(res[0].url)
                }
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            console.log(dataArr[imgField])
            dataArr[imgField].pop()
            showFailToast('上传失败')
            console.log(err)
        })
    }






    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message
        })
    }
    const onSubmit = async (value) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        
        GmsmyuyApi({
            data: JSON.stringify(formData.value),
            // data: formData.value,
        }).then(res => {
            closeToast();
            if (res.status == '+OK') {
                showDialog({
                    title: '提示',
                    message: '提交成功！',
                }).then(() => {
                    router.push('/')                         
                });
            } else {
                showDialog({
                    title: '提示',
                    message: '网络异常，请稍后重试！',
                })
            }
            
        }).catch(err => {
            closeToast();
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            })
        })
    }
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .dnt-box {
        border-bottom: 1px solid #efefef;
    }
</style>